package com.zerui.manager.app.deviceTouchSync.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.zerui.manager.app.scheduler.bean.JobBean;
import com.zerui.manager.app.scheduler.bean.JobConst;
import com.zerui.manager.app.scheduler.bean.ScheduleConstants;
import com.zerui.manager.app.scheduler.utils.ScheduleUtils;
import com.zerui.manager.deviceTouchSync.convertor.DeviceTouchSyncConvert;
import com.zerui.manager.deviceTouchSync.domainservice.DeviceTouchSyncRepository;
import com.zerui.manager.deviceTouchSync.entity.DeviceTouchSyncDO;
import com.zerui.manager.web.cmd.DeviceTouchSyncAddCmd;
import org.quartz.Scheduler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author wh
 * @create_time 2023-08-23 16:29
 */
@Component
@CatchAndLog
public class DeviceTouchSyncAddCmdExe {

    @Resource
    private DeviceTouchSyncRepository deviceTouchSyncRepository;


    /**
     * 保存门禁设备同步信息及开启线程执行操作
     *
     * @param addCmd
     */
    @Transactional(rollbackFor = Exception.class)
    public JobBean execute(DeviceTouchSyncAddCmd addCmd) {
        DeviceTouchSyncDO deviceTouchSyncDO = DeviceTouchSyncConvert.INSTANCE.convertDeviceTouchAddCmdToDeviceTouchDo(addCmd);
        Long id = deviceTouchSyncRepository.addDeviceTouchSync(deviceTouchSyncDO.toDomain());// 保存成功后，就启用线程
        deviceTouchSyncDO.setId(id); // 主键
        return initJobBean(deviceTouchSyncDO);
    }

    private JobBean initJobBean(DeviceTouchSyncDO syncDO) {
        // 构建一个新的训练任务
        JobBean job = new JobBean();
        job.setJobId(syncDO.getId()); // 任务ID
        job.setJobName("deviceSyncJob"); // 任务名称
        job.setJobGroup(JobConst.GROUP_DEVICE_TOUCH); // 训练模型分组
        job.setInvokeTarget("deviceSyncJob.run(\"" + syncDO.getId() + "\")");
        job.setCronExpression("0 0 * * * ?");
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_DO_NOTHING); // 放弃执行
        job.setConcurrent("1"); // 支持并发 & 多文件处理，支持多并发
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); // 0:暂停 1:启用
        return job;
    }
}
